package org.gongliang.config;

import java.util.Map;

import org.gongliang.common.enums.KCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;

import com.google.common.collect.Maps;

@Configuration
public class RedisConfig {

    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;

    @Bean
	public RedisTemplate<String, Object> redisTemplate() {
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		template.setKeySerializer(new JdkSerializationRedisSerializer());
		template.setHashKeySerializer(new JdkSerializationRedisSerializer());
		template.setHashValueSerializer(new JdkSerializationRedisSerializer());
		template.setValueSerializer(new JdkSerializationRedisSerializer());
		template.setConnectionFactory(jedisConnectionFactory);
		template.afterPropertiesSet();
        return template;
    }

	@Bean(name = "redisCacheManager")
	public CacheManager redisCacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
		RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
		redisCacheManager.setDefaultExpiration(KCache.halfHour.getExpires());
		redisCacheManager.setUsePrefix(true);
        Map<String,Long> expires=Maps.newHashMap();
		for (KCache rt : KCache.values()) {
			expires.put(rt.getCacheName(), rt.getExpires());
		}
        redisCacheManager.setExpires(expires);
        return redisCacheManager;
    }

    @Bean
	public Cache cache(CacheManager cacheManager) {
		return cacheManager.getCache(KCache.halfHour.getCacheName());
    }

	// @Bean
	// public KeyGenerator keyGenerator() {
	// return new KeyGenerator() {
	// @Override
	// public Object generate(Object target, Method method, Object... objects) {
	// StringBuilder sb = new StringBuilder();
	// sb.append(target.getClass().getName());
	// sb.append("." + method.getName());
	// return sb.toString();
	// }
	// };
	// /*
	// * java8->lambda实现 return (target, method, objects) -> { StringBuilder
	// * sb = new StringBuilder(); sb.append(target.getClass().getName());
	// * sb.append("." + method.getName()); return sb.toString(); };
	// */
	// }
}
